package com.z.redis.command.impl;

import com.z.redis.RedisCore;
import com.z.redis.command.Command;
import com.z.redis.command.CommandType;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import io.netty.channel.ChannelHandlerContext;

import java.util.Arrays;


/**
 * 实现了基础的Exists命令 检查键是否存在并返回对于的结果
 */
public class Exists implements Command {
    private BytesWrapper[] keys;
    @Override
    public CommandType type(){
        return CommandType.exists;
    }

    @Override
    public void setContent(Resp[] array){
        if (array.length < 2) {
            throw new IllegalArgumentException("ERR wrong number of arguments");
        }
        keys = Arrays.stream(array)
                .skip(1) // 跳过命令名
                .map(resp -> (BulkString) resp)
                .map(BulkString::getContent)
                .toArray(BytesWrapper[]::new);
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        long count = Arrays.stream(keys).filter(redisCore::exist).count();
        ctx.writeAndFlush(new RespInt((int)count));
    }
}
